import * as Cesium from 'cesium';

// 定义一个自定义的 Primitive 类，绘制线和面
class LineAndSurfacePrimitive extends Cesium.Primitive {
  constructor(options) {
    super(options);

    // 创建面：BoxGeometry 代表一个立方体
    this._boxGeometry = new Cesium.BoxGeometry({
      maximum: new Cesium.Cartesian3(1.0, 1.0, 1.0),
      minimum: new Cesium.Cartesian3(-1.0, -1.0, -1.0)
    });

    // 创建线：一个简单的 Polyline
    this._lineGeometry = new Cesium.PolylineGeometry({
      positions: [
        new Cesium.Cartesian3(-1.0, -1.0, 0.0), // 线段的起始点
        new Cesium.Cartesian3(1.0, 1.0, 0.0)    // 线段的终止点
      ]
    });

    this._color = options.color || Cesium.Color.RED;
  }

  // 提供绘制几何体的功能
  _createRenderResources (context) {
    // 创建面几何体
    const boxGeometry = Cesium.BoxGeometry.createGeometry(this._boxGeometry);
    const boxAppearance = new Cesium.PerInstanceColorAppearance({
      closed: true
    });

    // 创建线几何体
    const polylineGeometry = Cesium.PolylineGeometry.createGeometry(this._lineGeometry);
    const polylineAppearance = new Cesium.PolylineMaterialAppearance({
      material: Cesium.Material.fromType('Color', {
        color: this._color
      })
    });

    return {
      boxGeometry: boxGeometry,
      boxAppearance: boxAppearance,
      polylineGeometry: polylineGeometry,
      polylineAppearance: polylineAppearance
    };
  }

  // 渲染逻辑
  _draw (context, frameState) {
    const resources = this._createRenderResources(context);

    // 创建 GeometryInstance 和 Primitive
    const boxInstance = new Cesium.GeometryInstance({
      geometry: resources.boxGeometry,
      appearance: resources.boxAppearance
    });

    const polylineInstance = new Cesium.GeometryInstance({
      geometry: resources.polylineGeometry,
      appearance: resources.polylineAppearance
    });

    // 绘制面
    context.drawGeometryInstance(boxInstance);

    // 绘制线
    context.drawGeometryInstance(polylineInstance);
  }

  // 需要提供的其他方法（如更新、销毁等）
  update (time) {
    // 可以在这里做一些动态更新
  }

  isDestroyed () {
    return false;
  }

  destroy () {
    this._boxGeometry = null;
    this._lineGeometry = null;
  }
}

export default LineAndSurfacePrimitive;
